package com.jwater.core.net;

import java.io.Serializable;
import java.util.Arrays;

import com.jwater.core.common.S;
import com.jwater.core.serialize.SerializeFactory;

import jwater.org.apache.mina.core.buffer.IoBuffer;
/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class InvokePacket implements Serializable {
	private static final long serialVersionUID = -764679728097949219L;
	private short serializeType = SerializeFactory.DEFAULT_SERIALIZE_TYPE;
	private String clazzName;// 类名
	private String methodName;// 方法名
	private Object[] argObjs;// 参数对象

	public byte[] serialize() throws Exception {
		serializeType = SerializeFactory.getSerializeType(argObjs);
		byte[] classNameBytes = clazzName.getBytes(S.charset);
		byte[] methodNameBytes = methodName.getBytes(S.charset);
		byte[] data = SerializeFactory.getSerializeService(serializeType).serializeArray(argObjs);
		IoBuffer buffer = IoBuffer.allocate(14 + classNameBytes.length + methodNameBytes.length + data.length);
		buffer.putShort(serializeType);
		buffer.putInt(classNameBytes.length);
		buffer.put(classNameBytes);
		buffer.putInt(methodNameBytes.length);
		buffer.put(methodNameBytes);
		buffer.putInt(data.length);
		if (data.length > 0) {
			buffer.put(data);
		}
		return buffer.array();
	}

	public InvokePacket deserialize(byte[] data) throws Exception {
		IoBuffer buffer = IoBuffer.wrap(data);
		serializeType = buffer.getShort();

		int len = buffer.getInt();
		byte[] bytes = new byte[len];
		buffer.get(bytes);
		clazzName = new String(bytes, 0, bytes.length, S.charset);

		len = buffer.getInt();
		bytes = new byte[len];
		buffer.get(bytes);
		methodName = new String(bytes, 0, bytes.length, S.charset);

		len = buffer.getInt();
		if (len > 0) {
			bytes = new byte[len];
			buffer.get(bytes);
			argObjs = SerializeFactory.getSerializeService(serializeType).deserializeArray(bytes);
		} else {
			argObjs = new Object[0];
		}
		return this;
	}

	public short getSerializeType() {
		return serializeType;
	}

	public void setSerializeType(short serializeType) {
		this.serializeType = serializeType;
	}

	public String getClazzName() {
		return clazzName;
	}

	public void setClazzName(String clazzName) {
		this.clazzName = clazzName;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public Object[] getArgObjs() {
		return argObjs;
	}

	public void setArgObjs(Object[] argObjs) {
		this.argObjs = argObjs;
	}

	@Override
	public String toString() {
		return "InvokePacket [clazzName=" + clazzName + ", methodName=" + methodName + ", argObjs="
				+ Arrays.toString(argObjs) + "]";
	}
}
